<?php
namespace App\Admin\Socialite;

use GuzzleHttp\RequestOptions;
use Laravel\Socialite\Two\User;
use Laravel\Socialite\Two\AbstractProvider;
use Illuminate\Support\Arr;
use Illuminate\Http\RedirectResponse;

class WorkWeixinProvider extends AbstractProvider
{

    protected $scopes = ['snsapi_privateinfo'];

    protected $parameters = [
        'login_type' => 'CorpApp',
        'appid' => 'ww18c5ea4ad9f4e783',
    ];


    /**
     * 企业微信有appid和agentid两个oauth异性参数
     * https://developer.work.weixin.qq.com/document/path/98152
     */
    protected function getAuthUrl($state){
    	return $this->buildAuthUrlFromBase('https://login.work.weixin.qq.com/wwlogin/sso/login', $state);
    }


    protected function getCodeFields($state = null)
    {
        $fields = parent::getCodeFields($state);

        $fields['agentid'] = $fields['client_id'];
        unset($fields['client_id']);

        return $fields;
    }


    protected function getTokenUrl(){
        return 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?'.http_build_query([
            'corpid' => $this->parameters['appid'],
            'corpsecret' => $this->clientSecret,
        ]);
    }

    /**
     * @link https://developer.work.weixin.qq.com/document/path/98176
     * 如果报错60020 大概率是自建应用为设置可信IP的原因
     */
    protected function getUserByToken($token){
        $userUrl = 'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?'.http_build_query([
            'access_token' => $token,
            'corpsecret' => $this->getCode(),
        ]);

        $response = $this->getHttpClient()->get($userUrl);

        $user = json_decode($response->getBody(), true);

        if( $user['errcode']!=0 ){
            dd($user);
        }

        return $user;
    }

    protected function mapUserToObject(array $user){
        return (new User)->setRaw($user)->map([
            // 微信就返回这么一个信息
            'id'     => $user['userid'],
        ]);
    }
}